package com.zara.store.web.struts;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.zara.store.client.clientmodel.Basket;

public class PalcAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		HttpSession session = request.getSession();
		Basket basket = (Basket) session.getAttribute("palc");
		
		if(basket != null && form != null) {
			BasketForm customForm = (BasketForm) form;
			BasketAction.BasketActionHelper helper = new BasketAction.BasketActionHelper(customForm);
			String[] productAmount = customForm.getProductAmount();
			
			if(productAmount != null) {
				for(int i = 0; i < productAmount.length; i++) {
					if(!helper.isProductRemoved(i)) {
						basket.changeProductAmount(i, productAmount[i]);
						try {
							int a = Integer.parseInt(productAmount[i]);
							if(0 == a) {
								helper.addRemoved(i);
							}
						} catch(NumberFormatException e) {
						}
					}
				}
			}
			if(helper.hasRemoved()) {
				for(int i = productAmount.length-1; i >= 0; i--) {
					if(helper.isProductRemoved(i)) {
						basket.removeProduct(i);
					}
				}
			}
			if("Ordenar >".equals(customForm.getSubmit())) {
				return (mapping.findForward("palc-order"));
			}
		}

		return (mapping.findForward("success"));
	}

}